package com.hxy.springboot06.controller;

import com.hxy.springboot06.bean.User;
import com.hxy.springboot06.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
public class UserController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @PostMapping("/login")
    public String login(User user, HttpSession session, Model model){
        if(userMapper.findeUserByName(user.getUsername())!=null){
            String pwd=userMapper.findeUserByName(user.getUsername());
            if(pwd.equals(user.getPassword())){
                session.setAttribute("user",user);
                    return "redirect:/main";
            }
            model.addAttribute("msg","登陆失败,用户名或密码错误");
            return "login";
        }
//      if("admin".equals(user.getUsername())&&"123".equals(user.getPassword())) {
//          session.setAttribute("user",user);
//          return "redirect:/main";
//      }
      model.addAttribute("msg","登陆失败,用户名或密码错误");
      return "login";
    }
//    @ResponseBody
//    @GetMapping("/sql")
//    public String sql(){
//        jdbcTemplate.query("select * from user",new BeanPropertyRowMapper<>(User.class));
//       return "ok";
//    }
     @Autowired
    UserMapper userMapper;

   @GetMapping("basic_table.html")
    public String basic_table(Model model){
       List<User> users =userMapper.selectList(null);
       model.addAttribute("users",users);
       return "table/basic_table";
   }
    @GetMapping("save.html")
    public String saveUI(Model model){
        return "table/add";
    }
    @PostMapping("save")
    public String save(User user){
        int i=userMapper.insert(user);
        return "redirect:/basic_table.html";
    }
    @GetMapping("edit.html")
    public String editUI(Integer id, Model model){
        User user=userMapper.selectById(id);
        model.addAttribute("user",user);
        return "table/edit";
    }
    @PostMapping("edit")
    public String edit(User user){
       int i=userMapper.updateById(user);
        return "redirect:/basic_table.html";

}
    @GetMapping("del.html")
    public String edit(Integer id){
        userMapper.deleteById(id);
        return "redirect:/basic_table.html";
   }
}
